package com.dlry.web;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dlry.entity.DlLeave;
import com.dlry.entity.DlLoginuser;
import com.dlry.entity.DlMeetingRoom;
import com.dlry.entity.DlMeetingRoomBooking;
import com.dlry.entity.DlNotification;
import com.dlry.entity.DlShare;
import com.dlry.entity.DlTravelRequest;
import com.dlry.entity.validGroup.First;
import com.dlry.serviceImpl.LeaveService;
import com.dlry.serviceImpl.MeetingRoomBookingService;
import com.dlry.serviceImpl.MeetingRoomService;
import com.dlry.serviceImpl.NotificationService;
import com.dlry.serviceImpl.ShareService;
import com.dlry.serviceImpl.TravelService;
import com.dlry.serviceImpl.UserService;
import com.dlry.web.valid.PasswordForm;

@Controller

public class UserController extends BaseController {
	@Autowired
	private UserService userService;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private NotificationService notificationService;
	@Autowired
	private LeaveService leaveService;
	@Autowired
	private TravelService travelService;
	@Autowired
	private MeetingRoomService roomService;
	@Autowired
	private MeetingRoomBookingService bookingService;
	@Autowired
	private ShareService shareService;

	private static final Logger logger = LogManager.getFormatterLogger(UserController.class.getName());

	@RequestMapping("/register")
	public String register(Model model, HttpSession session) {
		if (!getPrincipal().equals("anonymousUser")) {
			return "redirect:/";
		}
		model.addAttribute("dlLoginuser", new DlLoginuser());
		// model.addAttribute("branchs", userService.findAllBranch());
		return "register_jsp";
	}

	@RequestMapping(value = "/doRegister", method = RequestMethod.POST)
	public String doRegister(DlLoginuser dlLoginuser, BindingResult result) throws Exception {
		dlLoginuser.setEnabled(false);
		dlLoginuser.setRoles("ROLE_USER");
		Timestamp timestamp = new Timestamp(new Date().getTime());
		dlLoginuser.setCreatedDate(timestamp);
		dlLoginuser.setUpdateDate(timestamp);
		userService.save(dlLoginuser);

		return "registerSuccess_jsp";
	}

	@RequestMapping("/login")
	public String login(Model model, HttpSession session) {
		if (!getPrincipal().equals("anonymousUser")) {
			return "redirect:/";
		}
		model.addAttribute("user", new DlLoginuser());
		return "login";
	}

	@RequestMapping("/usermanager")
	public String userManagerCenter(Model model, HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		model.addAttribute("duser", user);
		model.addAttribute("method", " 个人信息");
		model.addAttribute("title", "用户管理-个人信息");
		model.addAttribute("roler", "usermanager");
		return "usermanager/userinfo";
	}

	@RequestMapping("/usermanager/notification")
	public String userManagerNotification(@RequestParam(name = "current") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Long uId = user.getId();
		Long count = userService.getCountNotificationById(uId);
		Long pagecount = ((count - 1L) / 20L + 1L);
		Integer currentPage = current != null ? current : 0;
		List<DlNotification> notifications = userService.getNotificationsPagedById(uId, currentPage, 20);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", pagecount);
		model.addAttribute("notifications", notifications);
		model.addAttribute("duser", user);
		model.addAttribute("method", " 已发通知");
		model.addAttribute("title", "用户管理-通知管理");
		model.addAttribute("roler", "usermanager");
		return "usermanager/notification";
	}

	@RequestMapping("/usermanager/leave")
	public String userManagerLeave(@RequestParam(name = "current", defaultValue = "1") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Long uId = user.getId();
		Long count = userService.getCountLeaveById(uId);
		Long pagecount = ((count - 1L) / 20L + 1L);
		Integer currentPage = current != null ? current : 0;
		List<DlLeave> leaves = userService.getLeavesPagedById(uId, currentPage, 20);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", pagecount);
		model.addAttribute("leaves", leaves);
		model.addAttribute("duser", user);
		model.addAttribute("method", " 请假记录");
		model.addAttribute("title", "用户管理-请假记录");
		model.addAttribute("roler", "usermanager");
		return "usermanager/leave";

	}

	@RequestMapping("/usermanager/travel")
	public String userManagerTravel(@RequestParam(name = "current", defaultValue = "1") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Long uId = user.getId();
		Long count = userService.getCountTravelById(uId);
		Long pagecount = ((count - 1L) / 20L + 1L);
		Integer currentPage = current != null ? current : 0;
		List<DlTravelRequest> travelRequests = userService.getTravelRequestsPagedById(uId, currentPage, 20);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", pagecount);
		model.addAttribute("travelRequests", travelRequests);
		model.addAttribute("duser", user);
		model.addAttribute("method", " 出差记录");
		model.addAttribute("title", "用户管理-出差记录");
		model.addAttribute("roler", "usermanager");
		return "usermanager/travel";
	}

	@RequestMapping(value = "/{roler}/password")
	public String userManagerPasswordForm(Model model, @PathVariable("roler") String roler) {
		model.addAttribute("passwordForm", new PasswordForm());
		DlLoginuser user = userService.findByName(getPrincipal());
		model.addAttribute("duser", user);
		model.addAttribute("title", "修改密码");
		model.addAttribute("roler", roler);
		return roler + "/password";
	}

	@RequestMapping(value = "/{roler}/changepassword", method = RequestMethod.POST)
	public String userManagerChanagerPassword(@Valid PasswordForm passwordForm, BindingResult result, Model model,
			@PathVariable("roler") String roler) {
		if (result.hasErrors()) {
			model.addAttribute("roler", roler);
			return roler + "/password";
		}
		DlLoginuser user = userService.findByName(getPrincipal());
		if (!passwordEncoder.matches(passwordForm.getOldPassword(), user.getPassword())) {
			FieldError error = new FieldError("passwordForm", "oldPassword", "旧密码输入不正确");
			result.addError(error);
			model.addAttribute("errors", result);
			model.addAttribute("passwordForm", passwordForm);
			model.addAttribute("duser", user);
			model.addAttribute("title", "修改密码");
			model.addAttribute("roler", roler);
			return roler + "/password";
		}
		if (!passwordForm.getNewPassword1().equals(passwordForm.getNewPassword2())) {
			FieldError error = new FieldError("passwordForm", "newPassword1", "新的密码两次输入不一致");
			result.addError(error);
			model.addAttribute("errors", result);
			model.addAttribute("passwordForm", passwordForm);
			model.addAttribute("duser", user);
			model.addAttribute("title", "修改密码");
			model.addAttribute("roler", roler);
			return roler + "/password";
		}
		userService.changeUserPassword(user.getId(), passwordForm.getNewPassword1());
		// 记住日志
		logger.info(user.getName() + " changed password");
		model.addAttribute("roler", roler);
		return "redirect:/" + roler;
	}

	@RequestMapping(value = "/{roler}/userupdate", method = RequestMethod.POST)
	public String userUpdate(@Validated(value = { First.class }) DlLoginuser duser, BindingResult result, Model model,
			@PathVariable("roler") String roler) {
		DlLoginuser user = userService.findByName(getPrincipal());
		user.setRealName(duser.getRealName());
		user.setPhoneNumber(duser.getPhoneNumber());
		if (result.hasErrors()) {
			model.addAttribute("duser", user);
			model.addAttribute("errors", result);
			model.addAttribute("title", "用户管理-个人信息");
			model.addAttribute("roler", roler);
			return roler + "/userinfo";
		}
		userService.update(user);
		// 记录更新日志
		logger.info(user.getName() + " has been updated by " + getPrincipal());
		model.addAttribute("roler", roler);
		return "redirect:/" + roler;
	}

	@RequestMapping(value = "/adminmanager")
	public String adminManager(Model model) {
		DlLoginuser user = userService.findByName(getPrincipal());
		model.addAttribute("duser", user);
		model.addAttribute("method", " 个人信息");
		model.addAttribute("title", "管理员-个人信息");
		model.addAttribute("roler", "adminmanager");
		return "adminmanager/userinfo";
	}

	@RequestMapping("/adminmanager/notification")
	public String adminManagerNotification(@RequestParam(name = "current") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Integer currentPage = current != null ? current : 0;
		Page<DlNotification> notifications = notificationService.findAllPage(current - 1, 20);
		Integer pagecount = notifications.getTotalPages();
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", pagecount);
		model.addAttribute("notifications", notifications.getContent());
		model.addAttribute("duser", user);
		model.addAttribute("method", " 已发通知");
		model.addAttribute("title", "管理员-通知管理");
		model.addAttribute("roler", "adminmanager");
		return "adminmanager/notification";
	}

	@RequestMapping("/adminmanager/leave")
	public String adminManagerLeave(@RequestParam(name = "current", defaultValue = "1") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Integer currentPage = current != null ? current : 0;
		Page<DlLeave> leaves = leaveService.findAll(current - 1, 20);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", leaves.getTotalPages());
		model.addAttribute("leaves", leaves.getContent());
		model.addAttribute("duser", user);
		model.addAttribute("method", " 请假记录");
		model.addAttribute("title", "管理员-请假记录");
		model.addAttribute("roler", "adminmanager");
		return "adminmanager/leave";
	}

	@RequestMapping("/adminmanager/travel")
	public String adminManagerTravel(@RequestParam(name = "current", defaultValue = "1") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Integer currentPage = current != null ? current : 0;
		Page<DlTravelRequest> travelRequests = travelService.findAll(current - 1, 20);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", travelRequests.getTotalPages());
		model.addAttribute("travelRequests", travelRequests.getContent());
		model.addAttribute("duser", user);
		model.addAttribute("method", " 出差记录");
		model.addAttribute("title", "管理员-出差记录");
		model.addAttribute("roler", "adminmanager");
		return "adminmanager/travel";
	}

	@RequestMapping("/adminmanager/room")
	public String adminManagerRoom(@RequestParam(name = "current", defaultValue = "1") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Integer currentPage = current != null ? current : 0;
		Page<DlMeetingRoom> rooms = roomService.findAll(current - 1, 20);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", rooms.getTotalPages());
		model.addAttribute("rooms", rooms.getContent());
		model.addAttribute("duser", user);
		model.addAttribute("method", " 会议室管理");
		model.addAttribute("title", "管理员-会议室管理");
		model.addAttribute("roler", "adminmanager");
		return "adminmanager/room";
	}

	@RequestMapping("/adminmanager/booking")
	public String adminManagerBooking(@RequestParam(name = "current", defaultValue = "1") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Integer currentPage = current != null ? current : 0;
		Page<DlMeetingRoomBooking> bookings = bookingService.findAll(current - 1, 20);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", bookings.getTotalPages());
		model.addAttribute("bookings", bookings.getContent());
		model.addAttribute("duser", user);
		model.addAttribute("method", " 会议室预约管理");
		model.addAttribute("title", "管理员-会议室预约管理");
		model.addAttribute("roler", "adminmanager");
		return "adminmanager/bookings";
	}

	@RequestMapping("/adminmanager/user")
	public String adminManagerUser(@RequestParam(name = "current", defaultValue = "1") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Integer currentPage = current != null ? current : 0;
		Page<DlLoginuser> users = userService.findAll(current - 1, 20);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", users.getTotalPages());
		model.addAttribute("users", users.getContent());
		model.addAttribute("duser", user);
		model.addAttribute("method", " 注册用户管理");
		model.addAttribute("title", "管理员-注册用户管理");
		model.addAttribute("roler", "adminmanager");
		return "adminmanager/user";
	}

	// 异步更新用户enabled
	@RequestMapping("/adminmanager/setuserenable")
	public @ResponseBody Map<String, Object> setUserEnabled(HttpServletRequest request, HttpServletResponse response) {
		Long id = Long.parseLong(request.getParameter("id"));
		Boolean enabled = Boolean.parseBoolean(request.getParameter("enabled"));
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		System.out.println(id);
		System.out.println(enabled);
		DlLoginuser user = userService.findOne(id);
		if (user == null) {
			jsonMap.put("msg", "user does not exist！");
		} else {
			user.setEnabled(enabled);
			userService.update(user);
			logger.info(user.getName() + "的属性enabled被管理员" + getPrincipal() + "制为" + enabled);
			jsonMap.put("msg", "success");
		}
		return jsonMap;

	}

	// 异步更新用户权限
	@RequestMapping(value = "/adminmanager/setuserrole", produces = "application/json")
	public @ResponseBody Map<String, Object> setUserRoler(HttpServletRequest request, HttpServletResponse response) {
		Long id = Long.parseLong(request.getParameter("id"));
		String roler = request.getParameter("roler");
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		System.out.println(id);
		System.out.println(roler);
		DlLoginuser user = userService.findOne(id);
		if (user == null) {
			jsonMap.put("msg", "user does not exist！");
		} else {
			user.setRoles(roler);
			userService.update(user);
			logger.info(user.getName() + "的权限被管理员" + getPrincipal() + "制为" + roler);
			jsonMap.put("msg", "success");
		}
		return jsonMap;

	}

	@RequestMapping("/adminmanager/share")
	public String adminManagerShare(@RequestParam(name = "current", defaultValue = "1") Integer current, Model model,
			HttpSession session) {
		DlLoginuser user = userService.findByName(getPrincipal());
		Integer currentPage = current != null ? current : 0;
		Page<DlShare> shares = shareService.findAll(current - 1, 20);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pagecount", shares.getTotalPages());
		model.addAttribute("shares", shares.getContent());
		model.addAttribute("duser", user);
		model.addAttribute("method", " 共享管理");
		model.addAttribute("title", "管理员-共享管理");
		model.addAttribute("roler", "adminmanager");
		return "adminmanager/share";
	}

	@RequestMapping("/accessdenied")
	public String accessDenied() {
		return "accessdenied_jsp";
	}
}
